from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.db.models import F, Q, Count, CharField, Case, When, Value, IntegerField, ExpressionWrapper, Func, Max
from .models import WealthOffsitefund, WealthNetvalue
import requests
from lxml import etree
import re
import time
from datetime import datetime
import pandas as pd

# 主页面
def fund_main(request):
    return render(request, 'fund_main.html')
def fund_main_get(request):
    netvalue = list(WealthNetvalue.objects.filter(code='008481').order_by('date').values())
    data = {
        'netvalue': netvalue,
    }
    return JsonResponse(data, safe=False)
@csrf_exempt
def fund_main_post(request):
    fundcode = request.POST.get("fundcode") # 基金代码 
    # 获取基金信息
    try:
        url_fund = f'http://fund.eastmoney.com/{fundcode}.html'
        res = requests.get(url_fund) # 获取天天基金的基金详情页
        res = res.content.decode(encoding='utf-8') # 将网页格式转化为UTF-8
        tree = etree.HTML(res) # 解析网页HTML
        name = tree.xpath('//div[@class="fundDetail-tit"]/div/text()')[0] # 基金名称
        fund_type = tree.xpath('//div[@class="infoOfFund"]/table/tr[1]/td[1]/a/text()')[0] # 基金类型
        risk_level = tree.xpath('//div[@class="infoOfFund"]/table/tr[1]/td[1]/text()')[1].replace("\xa0\xa0|\xa0\xa0", "") # 风险等级
        fund_manager = tree.xpath('//div[@class="infoOfFund"]/table/tr[1]/td[3]/a/text()')[0] # 基金经理
        established_date = tree.xpath('//div[@class="infoOfFund"]/table/tr[2]/td[1]/text()')[0].replace('：', '') # 成立日期
        fund_company = tree.xpath('//div[@class="infoOfFund"]/table/tr[2]/td[2]/a/text()')[0] # 基金公司
        fund_scale = tree.xpath('//div[@class="infoOfFund"]/table/tr[1]/td[2]/text()')[0].replace('：', '') # 基金规模
        fund_scale = re.sub(r'（.*?）', '', fund_scale) # 基金规模去除时间
        create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 获取当前时间作为记录时间
    except Exception as e:
       status_fund = str(e) # 发送前端消息标记
       name = ''

    if name:
        # 添加/更新基金信息
        try:
            if WealthOffsitefund.objects.filter(code=fundcode): # 判断基金代码是否已经存在
                # 如果存在，更新基金信息
                WealthOffsitefund.objects.filter(code=fundcode).update(
                    name = name,
                    fund_type = fund_type,
                    risk_level = risk_level,
                    fund_manager = fund_manager,
                    established_date = established_date,
                    fund_company = fund_company,
                    fund_scale = fund_scale,
                    update_time = create_time
                    )
                status_fund = 'update' # 发送前端消息标记
            else:
                # 如果不存在，添加基金
                WealthOffsitefund.objects.create(
                    code = fundcode,
                    name = name,
                    fund_type = fund_type,
                    risk_level = risk_level,
                    fund_manager = fund_manager,
                    established_date = established_date,
                    fund_company = fund_company,
                    fund_scale = fund_scale,
                    create_time = create_time
                )
                status_fund = 'create' # 发送前端消息标记
        except Exception as e:
            status_fund = str(e) # 发送前端消息标记

    # 获取基金历史净值
    if not WealthNetvalue.objects.filter(code=fundcode):
        try:
            currenttime = int(time.time() * 1000)
            url_fund_netvalue = f'http://api.fund.eastmoney.com/f10/lsjz?callback=&fundCode={fundcode}&pageIndex=1&pageSize=1000&startDate=&endDate=&_={currenttime}'   
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36',
                'Referer': 'http://fundf10.eastmoney.com/jjjz_008060.html',
                'Host': 'api.fund.eastmoney.com'
            }
            res = requests.get(url_fund_netvalue, headers=headers)
            df = pd.DataFrame(res.json()['Data']['LSJZList'])
            df[['DWJZ', 'LJJZ', 'JZZZL']] = df[['DWJZ', 'LJJZ', 'JZZZL']].apply(pd.to_numeric, errors='coerce').fillna(0)
            create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 获取当前时间作为记录时间
            instances = [WealthNetvalue(code=fundcode, date=row['FSRQ'], netvalue=row['DWJZ'], accnetvalue=row['LJJZ'], 
                                        day_increase=row['JZZZL'], dividend=row['FHSP'], create_time=create_time) for index, row in df.iterrows()]
            print(instances)
            WealthNetvalue.objects.bulk_create(instances) # 使用 bulk_create 批量保存实例到数据库
            status_netvalue = 'create'
        except Exception as e:
            status_netvalue = str(e) # 发送前端消息标记
    else:
        status_netvalue = 'undo'

    message = {
        'status_fund': status_fund,
        'status_netvalue': status_netvalue,
        'fund_name': name,
    }
    return JsonResponse(message, safe=False)